package com.webserver.core;

import com.webserver.controller.ArticleController;
import com.webserver.controller.UserController;
import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.File;
import java.net.URISyntaxException;

public class DispatcherServlet {
    private static DispatcherServlet instance = new DispatcherServlet();
    private static File staticDir;

    static {
        try {
            File root = new File(
                    DispatcherServlet.class.getClassLoader().getResource(".").toURI()
            );
            staticDir = new File(root,"static");
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }

    private DispatcherServlet() {
    }

    public static DispatcherServlet getInstance() {
        return instance;
    }

    public void service(HttpServletRequest request, HttpServletResponse response){
        String path = request.getRequestURI();
        System.out.println("path:"+path);
        if ("/regUser".equals(path)){
            UserController controller = new UserController();
            controller.reg(request,response);
        }else if ("/loginUser".equals(path)){
            UserController controller = new UserController();
            controller.login(request,response);
        }else if ("/writeArticle".equals(path)){
            ArticleController controller = new ArticleController();
            controller.writeArticle(request,response);
        }else {
            File file = new File(staticDir, path);
            if (file.exists()){
                response.setEntity(file);
            }else {
                response.setStatusCode(404);
                response.setStatusReason("NotFound");
                file = new File(staticDir,"404.html");
                response.setEntity(file);
            }
        }
        response.addHeader("Server", "BirdWebServer");
    }
}
